package cn.echo.sharding.algorithm;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.*;


/**
 * 按旬拆表方式
 * @author lonyee
 *
 */
public class TendaysRangeShardingAlgorithm implements RangeShardingAlgorithm<Date> {

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Date> rangeShardingValue) {
        Set<String> collect = new HashSet<>();
        Range<Date> valueRange = rangeShardingValue.getValueRange();
        Date startTime = valueRange.lowerEndpoint();
        Date endTime = valueRange.upperEndpoint();
        
        Calendar calendar = Calendar.getInstance();
        while (startTime.getTime()<=endTime.getTime()){
    		String shardfix = this.getShardfix(startTime);
            for (String each : collection) {
                if (each.endsWith(shardfix)) {
                    collect.add(each);
                }
            }
            calendar.setTime(startTime);
            calendar.add(Calendar.DATE, 1);
            startTime = calendar.getTime();
        }
        return collect;
    }
    
    //按旬拆表
    private String getShardfix(Date date) {
    	Calendar calendar = Calendar.getInstance();
 		calendar.setTime(date);
 		String shardfix = ""+ calendar.get(Calendar.YEAR) + (calendar.get(Calendar.MONTH) + 1);
 		int day = calendar.get(Calendar.DAY_OF_MONTH);
 		if (day<=10) {
 			shardfix +="_01";
 		} else if (day<=20) {
 			shardfix +="_02";
 		} else {
 			shardfix +="_03";
 		}
 		return shardfix;
    }
}
